package com.adv.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.adv.web.common.BaseController;
import com.adv.web.handle.WeixinHandle;
import com.adv.web.handle.WeixinMatcher;
import com.adv.web.service.MenuService;

@Controller
@RequestMapping("/wx/authen")
public class CoreController extends BaseController{

	@Autowired
	private WxMpService wxMpService;
	
	@Autowired
	private WxMpInMemoryConfigStorage wxMpConfigStorage;
	
	@Autowired
	private WxMpMessageRouter wxMpMessageRouter;
	
	/**  
     * 微信公众号webservice主服务接口，提供与微信服务器的信息交互  
     *   
     * @param request  
     * @param response  
     * @throws Exception  
     */ 
	@RequestMapping("portal")
	 protected void service(HttpServletRequest request, HttpServletResponse response)
		      throws ServletException, IOException {
		  String signature = request.getParameter("signature");
		  String nonce = request.getParameter("nonce");
		  String timestamp = request.getParameter("timestamp");
		  response.setContentType("text/html;charset=utf-8");
		  response.setStatus(HttpServletResponse.SC_OK);
		  try {
		  if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
		    // 消息签名不正确，说明不是公众平台发过来的消息
		    response.getWriter().println("非法请求");
		    return;
		  }
		  String echostr = request.getParameter("echostr");
		  if (StringUtils.isNotBlank(echostr)) {
		    // 说明是一个仅仅用来验证的请求，回显echostr
		    response.getWriter().println(echostr);
		    return;
		  }
		  String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ? 
				  "raw" :request.getParameter("encrypt_type");
		  WxMpXmlMessage inMessage = null;
		  if ("raw".equals(encryptType)) {
		    // 明文传输的消息
		    inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
		  } else if ("aes".equals(encryptType)) {
		    // 是aes加密的消息
		    String msgSignature = request.getParameter("msg_signature");
		    inMessage = WxMpXmlMessage.fromEncryptedXml
		    		(request.getInputStream(), wxMpConfigStorage, timestamp, nonce, msgSignature);
		  } else {
		    response.getWriter().println("不可识别的加密类型");
		    return;
		  }
		  MenuService.createmenu(wxMpService);
		  wxMpMessageRouter
		    .rule()
		    .async(false)
		    .msgType(WxConsts.XML_MSG_TEXT)
		    .matcher(new WeixinMatcher())
		    .handler(new WeixinHandle())
		    .end()
		    .rule()
            .async(false)
            .msgType(WxConsts.XML_MSG_EVENT)
            .event(WxConsts.EVT_SUBSCRIBE) 
            .handler(new WeixinHandle())
            .end()
            .rule()
            .async(false)
            .msgType(WxConsts.XML_MSG_EVENT)
            .event(WxConsts.EVT_CLICK)
            .handler(new WeixinHandle())
            .end();
		  
		  WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);

		  if (outMessage != null) {
		    if ("raw".equals(encryptType)) {
		      response.getWriter().write(outMessage.toXml());
		  	
		    } else if ("aes".equals(encryptType)) {
		      response.getWriter().write(outMessage.toEncryptedXml(wxMpConfigStorage));
		    }
		    return;
		  }
		  
		  } catch (Exception e) {
				e.printStackTrace();
			}finally{
				response.getWriter().close();
			}
		  
	}
	
	
	
}
